package com.engineering.elink.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.engineering.elink.co.CompanyCo;
import com.engineering.elink.co.CompanyInsertCo;
import com.engineering.elink.co.CompanyUpdateCo;
import com.engineering.elink.co.UserCo;
import com.engineering.elink.common.Constant;
import com.engineering.elink.common.Pagination;
import com.engineering.elink.dao.CompanyMapper;
import com.engineering.elink.dao.TokenAuthenticationMapper;
import com.engineering.elink.dao.UserMapper;
import com.engineering.elink.domain.Company;
import com.engineering.elink.domain.User;
import com.engineering.elink.service.CompanyService;
import com.engineering.elink.service.RedisService;
import com.engineering.elink.service.VerificationService;
import com.engineering.elink.util.global.TokenExpireTime;
import com.engineering.elink.util.io.ImgUtil;
import com.engineering.elink.util.token.MD5Util;
import com.engineering.elink.util.token.TokenGenerator;
import com.engineering.elink.util.tool.UUIDUtil;
import com.engineering.elink.util.verify.VerifyCodeUtils;

@Service
public class CompanyServiceImpl implements CompanyService{

	@Autowired
	private CompanyMapper companyMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private RedisService redisService;
	@Autowired
	private TokenAuthenticationMapper tokenAuthenticationMapper;
	@Autowired
	private VerificationService verificationService;
	
	@Override
	public void updateCompanyInfo(CompanyUpdateCo companyUpdateCo) {
		Map<String,Object> companyMap = companyMapper.selectBaseInfoByUserId(companyUpdateCo.getUserId());
		if (companyMap != null) {
			if ( !companyMap.get("logo").equals(companyUpdateCo.getLogo())) {
				String fileName = UUIDUtil.getUUID() + ".png";
				String filePath = Constant.imageFilePath + fileName;
				System.out.println("beginning transcode base64 to localImage");
				ImgUtil.GenerateImage(companyUpdateCo.getLogo(), filePath);
				System.out.println("transcode finished");
				companyUpdateCo.setLogo(Constant.webPicPath+"/upload/file/image/"+fileName);
			}
			companyUpdateCo.setUpdateTime(new Date());
			companyUpdateCo.setAuthStatus(Constant.companyReviewPending);
			companyMapper.updateByUserIdSelective(companyUpdateCo);
		}
	}

	@Override
	public Map<String, Object> login(String email, String passwd) {
		passwd = MD5Util.getMD5String(passwd);
		User user = userMapper.selectByEmailAndPasswd(Constant.companyUserType, email, passwd);
		System.out.println(333);
		if (user != null) {
			System.out.println(444444);
			Map<String, Object> map = new HashMap<String, Object>();
			String seed = TokenGenerator.getSeed(user.getUserId());
			String authToken = TokenGenerator.getToken();
			map.put("seed", seed);
			map.put("authToken", authToken);
			map.put("user", user);
			return map;
		}
		return null;
	}
	@Override
	public void regCompanyWithVerifyCode(String verifyToken,
			String verifyCode) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> dataMap = new HashMap<String, Object>();
		dataMap.put("verifyCode", verifyCode);
		map.put("data", dataMap);
		// status == 1 发送验证码 第一步
		map.put("status", 1);
		map.put("type", Constant.regCompanyCache);
		redisService.putSeedObjectMap(Constant.redisCommonCache, verifyToken,
				map, Constant.regCompanyCacheOneStepValidTime);
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean regCompanyWithSendPhoneCode(String phone,
			String verifyToken, String verifyCode) {
		Map<String, Object> map = (Map<String, Object>) redisService
				.getObjectBySeed(Constant.redisCommonCache, verifyToken);
		if (map == null
				|| !map.containsKey("object")
				|| map.get("object") == null
				|| !((Map<String, Object>) map.get("object"))
						.containsKey("status")
				|| !((Map<String, Object>) map.get("object"))
						.containsKey("type")
				|| !((Map<String, Object>) map.get("object"))
						.containsKey("data")) {
			return false;
		}
		Map<String, Object> tmpMap = (Map<String, Object>) map.get("object");
		int status = (int) tmpMap.get("status");
		int type = (int) tmpMap.get("type");
		tmpMap = (Map<String, Object>) tmpMap.get("data");
		String verifyCodeInRedis = (String) tmpMap.get("verifyCode");
		System.out.println(map.toString());
		System.out.println(((Map<String, Object>) ((Map<String, Object>) map
				.get("object")).get("data")).get("verifyCode"));
		if ((status == 1 || status == 2)  && type == Constant.regCompanyCache && verifyCode.equals(verifyCodeInRedis)) {
			// 发送验证码
			verifyCode = VerifyCodeUtils.generateNumberCode(4);
			// todo
			System.out.println("手机短信验证码为=" + verifyCode);
			verificationService.sendPhoneCode(phone, verifyCode);
			map.clear();
			Map<String, Object> dataMap = new HashMap<String, Object>();
			dataMap.put("phone", phone);
			dataMap.put("verifyCode", verifyCode);
			map.put("data", dataMap);
			// status == 2 发送短信 第二步
			map.put("status", 2);
			map.put("type", Constant.regCompanyCache);
			redisService.putSeedObjectMap(Constant.redisCommonCache,
					verifyToken, map, Constant.regCompanyCacheTwoStepValidTime);
			return true;
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean regCompanyWithCheckPhoneCode(String email, String phone,
			String passwd, String verifyToken, String verifyCode) {
		Map<String, Object> map = (Map<String, Object>) redisService
				.getObjectBySeed(Constant.redisCommonCache, verifyToken);
		if (map == null
				|| !map.containsKey("object")
				|| map.get("object") == null
				|| !((Map<String, Object>) map.get("object"))
						.containsKey("status")
				|| !((Map<String, Object>) map.get("object"))
						.containsKey("type")
				|| !((Map<String, Object>) map.get("object"))
						.containsKey("data"))
			return false;
		Map<String, Object> tmpMap = (Map<String, Object>) map.get("object");
		int status = (int) tmpMap.get("status");
		int type = (int)tmpMap.get("type");
		tmpMap = (Map<String, Object>) tmpMap.get("data");
		String verifyCodeInRedis = (String) tmpMap.get("verifyCode");
		String phoneInRedis = (String) tmpMap.get("phone");
		System.out.println(map.toString());
		System.out.println(((Map<String, Object>) ((Map<String, Object>) map
				.get("object")).get("data")).get("verifyCode"));
		if ((status == 2 || status == 3)  && type == Constant.regCompanyCache && verifyCode.equals(verifyCodeInRedis)
				&& phone.equals(phoneInRedis)) {
			map.clear();
			Map<String, Object> dataMap = new HashMap<String, Object>();
			dataMap.put("phone", phone);
			dataMap.put("passwd", passwd);
			dataMap.put("email", email);
			map.put("data", dataMap);
			// status == 3 校验手机验证码 并存储基本信息
			map.put("status", 3);
			map.put("type", Constant.regCompanyCache);
			redisService.putSeedObjectMap(Constant.redisCommonCache, verifyToken, map, Constant.regCompanyCacheThreeStepValidTime);
			return true;
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	@Transactional
	public Map<String,Object> regCompanyWithBaseInfo(CompanyInsertCo companyInsertCo,
			String verifyToken) {
		Map<String, Object> map = (Map<String, Object>) redisService.getObjectBySeed(Constant.redisCommonCache, verifyToken);
		if (map == null|| !map.containsKey("object")|| map.get("object") == null
				|| !((Map<String, Object>) map.get("object")).containsKey("status")
				|| !((Map<String, Object>) map.get("object")).containsKey("type")
				|| !((Map<String, Object>) map.get("object")).containsKey("data")) {
			return null;
		}
		Map<String, Object> tmpMap = (Map<String, Object>) map.get("object");
		int status = (int) tmpMap.get("status");
		int type = (int) tmpMap.get("type");
		System.out.println("###########1"+status);
		if (status == 3 && type == Constant.regCompanyCache) {
			System.out.println("###########2");
			// 写入用户数据等很多别的
			Map<String, Object> dataMap = (Map<String, Object>) tmpMap
					.get("data");
			if (dataMap == null || !dataMap.containsKey("phone")
					|| !dataMap.containsKey("email")
					|| !dataMap.containsKey("passwd")) {
				System.out.println("###########3");
				return null;
			}
			System.out.println("###########4");
			String phone = (String) dataMap.get("phone");
			String email = (String) dataMap.get("email");
			String passwd = (String) dataMap.get("passwd");
			redisService.delObjectBySeed(Constant.redisCommonCache, verifyToken);

			System.out.println("###########5");
			// 生成新用户数据 用户ID和密码
			UserCo userCo = new UserCo();
			String userId = UUIDUtil.getUUID();
			userCo.setUserId(userId);
			userCo.setPasswd(MD5Util.getMD5String(passwd));
			userCo.setPhone(phone);
			userCo.setEmail(email);
			userCo.setCreateTime(new Date());
			userCo.setUserType(Constant.companyUserType);
			userMapper.insertSelective(userCo);

			System.out.println("###########6");
			// 将用户令牌存入缓存
			String seed = TokenGenerator.getSeed(userCo.getUserId());
			String authToken = TokenGenerator.getToken();
			map.put("authToken", authToken);
			map.put("userId", userCo.getUserId());
			System.out.println("####################3");
			redisService.putSeedObjectMap(Constant.tokenAuthenticationCache,seed, map, Constant.validTime);
			// 将用户令牌存入持久化
			map.clear();
			map.put("seed", seed);
			map.put("userId", userCo.getUserId());
			map.put("expireTimeDiff", TokenExpireTime.AuthTokenTTL);
			map.put("token", authToken);
			tokenAuthenticationMapper.insertAuthToken(map);

			System.out.println("###########7");
			map.clear();
			map.put("seed", seed);
			map.put("authToken", authToken);
			
			// 图片base64转换
			String fileName = UUIDUtil.getUUID() + ".png";
			String filePath = Constant.imageFilePath + fileName;
			System.out.println("beginning transcode base64 to localImage");
			ImgUtil.GenerateImage(companyInsertCo.getLogo(), filePath);
			System.out.println("transcode finished");
			companyInsertCo.setLogo("http://116.62.10.111/upload/file/image/"+fileName);
			
			companyInsertCo.setCompanyId(userId);
			companyInsertCo.setUserId(userId);
			companyInsertCo.setCreateTime(new Date());
			companyInsertCo.setCreateUserId(userId);
			companyInsertCo.setAuthStatus(Constant.companyReviewPending);
			companyMapper.insertSelective(companyInsertCo);
			return map;
		}
		return null;
	}

	@Override
	public Map<String, Object> getBaseInfoByUserId(String userId) {
		return companyMapper.selectBaseInfoByUserId(userId);
	}

	@Override
	public Map<String, Object> getBaseInfoByCompanyId(String companyId) {
		return companyMapper.selectBaseInfoByCompanyId(companyId);
	}

	@Override
	public Map<String, Object> getRecruit(String companyId) {
		Map<String,Object> map = userMapper.selectByUserId(companyId);
		if (map != null && map.containsKey("userType") && map.get("userType").equals(Constant.companyUserType)) {
			return companyMapper.getRecruit(companyId);
		}
		return null;
	}

	@Override
	public Map<String, Object> getResource(String companyId) {
		Map<String,Object> map = userMapper.selectByUserId(companyId);
		if (map != null && map.containsKey("userType") && map.get("userType").equals(Constant.companyUserType)) {
			return companyMapper.getResource(companyId);
		}
		return null;
	}

	@Override
	public Map<String, Object> getBasicFacts(String companyId) {
		Map<String,Object> map = userMapper.selectByUserId(companyId);
		if (map != null && map.containsKey("userType") && map.get("userType").equals(Constant.companyUserType)) {
			return companyMapper.getBasicFacts(companyId);
		}
		return null;
	}

	@Override
	public Company getCurrentCompanyInfo(String userId) {
		return companyMapper.selectCurrentCompanyInfo(userId);
	}

	@Override
	public List<Map<String, Object>> getPraiseCompany(int count) {
		return companyMapper.getPraiseCompany(count);
	}

	@Override
	public Map<String, Object> getStatistics() {
		return companyMapper.getStatistics();
	}

	@Override
	public Map<String, Object> getCompanyList(CompanyCo co) {
		Map<String , Object>map= new HashMap<String, Object>();
		map.put("list",companyMapper.getCompanyList(co));
		map.put("Pagination", new Pagination(co, companyMapper.selectCountCompanyList(co)));
		return map;
	}
}
